package cn.com.basic.framework.aliyun.odps;

import cn.com.basic.framework.aliyun.odps.error.OdpsError;
import cn.com.basic.framework.exception.enums.errors.SystemError;
import cn.com.basic.framework.exception.exceptions.SysException;
import com.aliyun.odps.Instance;
import com.aliyun.odps.OdpsException;
import com.aliyun.odps.task.SQLTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ODPS SQL操作实现类
 *
 * @author zhuxj
 */
public class OdpsSqlManager {

    private static Logger logger = LoggerFactory.getLogger(OdpsSqlManager.class);
    private OdpsManager manager;

    public OdpsSqlManager(OdpsManager manager) {
        this.manager = manager;
    }

    /**
     * 执行SQL操作
     *
     * @param sql 待执行sql
     * @return {@link Instance}
     */
    public Instance execute(String sql) {
        Instance i = null;
        try {
            i = SQLTask.run(this.manager.getOdps(), sql);
            i.waitForSuccess();
            return i;
        } catch (OdpsException e) {
            logger.error(e.getMessage(), e);
            throw SysException.newException(OdpsError.EXECUTE_SQL_ERROR, e);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw SysException.newException(SystemError.SYSTEM_ERROR, e);
        }
    }


    public void setManager(OdpsManager manager) {
        this.manager = manager;
    }
}
